<?php
include_once(dirname(__FILE__).'/db.class.php');
include_once(dirname(__FILE__).'/hmongo.class.php');
include_once(dirname(__FILE__).'/../lib/smarty/Smarty.class.php');
class Lxbase extends Lxdb
{
    public $userinfo;
    public $smarty;
    public $basehost;

    //获取配置文件数组
    public static function getconfig($cname){
        return include(dirname(__FILE__).'/../conf/'.$cname.'.config.php');
    }
    //SMARTY定义
    public function smarty($dir='')
    {
        $smarty_config = Lxbase::getconfig("smarty");
        $smarty = new Smarty();
        $smarty->caching=$smarty_config["cache"];
        $smarty->cache_lifetime=$smarty_config["ctime"];
        $smarty->template_dir = $smarty_config["templates"].$dir; //设置模板目录
        $smarty->compile_dir = $smarty_config["templates_c"]; //设置编译目录
        $smarty->cache_dir = $smarty_config["templates_c"]; //缓存文件夹
        if(!is_dir($smarty->cache_dir)){@mkdir($smarty->cache_dir);}
        $smarty->left_delimiter = $smarty_config["left"];   //定义左边
        $smarty->right_delimiter = $smarty_config["right"]; //定义右边
        return  $smarty;
    }

    //字符串截断工具
    public function cutstr_utf8($str,$length,$ti)
    {
        $str_cut=mb_substr($str,0,$length,'utf-8').$ti;
        return $str_cut;
    }

    //分页
    public function termpage($table,$where,$sort,$page,$pagesize)
    {
        if(!empty($sort)){$sort = implode("&",$sort)."&";}else{$sort='';}
        $num = $this->numdata($table,$where);
        if($num!=0){
            if($num<$pagesize){$page_num=1;}
            if($num%$pagesize)
            {
                $page_num=(int)($num/$pagesize)+1;
            }else{
                $page_num=$num/$pagesize;
            }
        }else{
            $page_num=0;
        }
        if($page_num>1)
        {
            $pagestr="共{$page_num}页，每页{$pagesize}条，<a href='?{$sort}page=1'>首页</a> ";
            if($page_num>10)
            {
                $pagel=($page+5)>$page_num?$page_num:$page+5;
                $j= ($page-5)<1?1:$page-5;
            }else{
                $pagel=$page_num;
                $j=1;
            }
            for($i=$j;$i<=$pagel;$i++)
            {
                if($i==$page)
                {
                    $pagestr.=" <font color='cuti red'>{$i}</font> ";
                }else{
                    $pagestr.=" <a href='?{$sort}page={$i}'>{$i}</a> ";
                }
            }
            $pagestr.=" <a href='?{$sort}page={$page_num}'>尾页</a>";
        }else{
            $pagestr="共1页，每页{$pagesize}条";
        }
        return $pagestr;
    }
    //GET访问
    public function call_get($url){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,30);
        curl_setopt($ch,CURLOPT_TIMEOUT,300);
		curl_setopt($ch,CURLOPT_SAFE_UPLOAD,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch,CURLOPT_HEADER, FALSE);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
        curl_setopt($ch,CURLOPT_URL,$url);
        $ret = curl_exec($ch);
        curl_close($ch);
        return $ret;
    }
    //POST访问
    public function call_post($url,$data){
        $ch = curl_init();
        //$header = array('Content-Type: text/html; charset=utf-8');
        curl_setopt($ch,CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,30);
        curl_setopt($ch,CURLOPT_TIMEOUT,300);
        curl_setopt($ch,CURLOPT_SAFE_UPLOAD,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch,CURLOPT_HEADER, FALSE);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch,CURLOPT_URL,$url);
        //curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $ret = curl_exec($ch);
        curl_close($ch);
        return $ret;
    }
	
	 //POST访问
    public function call_post_wq($url,$data){
        $ch = curl_init();
        $header = array('Content-Type: text/html; charset=utf-8');
        curl_setopt($ch,CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,30);
        curl_setopt($ch,CURLOPT_TIMEOUT,300);
        curl_setopt($ch,CURLOPT_SAFE_UPLOAD,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch,CURLOPT_HEADER, FALSE);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $ret = curl_exec($ch);
        curl_close($ch);
        return $ret;
    }


    //路由解析
    public static function urlreload($url,$type=0){
        $webinfo = Lxbase::getconfig("web");
        $type = empty($type)?$webinfo["urltype"]:intval($type);
        if($type==2){
            $url = trim(stristr($url,"?"),"?");
            $urlarr = explode(",",$url);
            $urlinfo["path"] = array_shift($urlarr);
            $urlinfo["model"] = array_shift($urlarr);
            $urlinfo["function"] = array_shift($urlarr);
            if(!empty($urlarr) && count($urlarr)>0){
                unset($_GET);
                foreach($urlarr as $k=>$v){
                    $get = explode("=",$v);
                    $_GET[$get[0]]=$get[1];
                }
            }
        }elseif($type==3){
			$pos = stristr($url,"?");
			if($pos === false){
				$url=stristr($url,".php");
			}else{
				$url=stristr($url,"?");
			}
            $urlarr = explode("/",$url);
            if(count($urlarr)>1){
                array_shift($urlarr);
                $urlinfo["path"]=array_shift($urlarr);
                $urlinfo["model"]=array_shift($urlarr);
                $urlinfo["function"]=array_shift($urlarr);
                if(!empty($urlarr) && count($urlarr)>0){
                    unset($_GET);
                    foreach($urlarr as $k=>$v){
                        $get = explode("=",$v);
                        $_GET[$get[0]]=$get[1];
                    }
                }
            }else{
                $urlinfo=array();
            }
        }else{
            $urlinfo["path"] = @strtolower(trim($_GET["g"]));
            $urlinfo["model"] = @strtolower(trim($_GET["m"]));
            $urlinfo["function"] = @strtolower(trim($_GET["a"]));
        }
        return $urlinfo;
    }

    //跳转登录页
    public static function gologin($type=0){

        $type = empty($type)?$webinfo["urltype"]:intval($type);
        if($type==2){
            $url = "index.php?user,member,login";
        }elseif($type==3){
            $url = "index.php/user/member/login";
        }else{
            $url = "index.php?g=user&m=member&a=login";
        }
        echo "<script>top.location.href='{$url}'</script>";
        exit;
    }

    //初始化
    public function setinit($path){
        $this->userinfo = $_SESSION["userinfo"];
        $this->smarty = $this->smarty($path);
        $_GET = $this->pram_deep($_GET);
        $_POST = $this->pram_deep($_POST);
        $webinfo = Lxbase::getconfig("web");
        $this->basehost = $webinfo["basehost"];
        $this->smarty->clearAllAssign();
        $this->smarty->assign("ipath",$webinfo["stadir"]);
        $this->smarty->assign("upath",$webinfo["updir"]);
    }

    //初始化mongo
    public function mongo(){
		$mdbinfo = Lxbase::getconfig("db");
        $mongo = new HMongodb($mdbinfo['mongo_server']);
        $mongo->selectDb($mdbinfo['mongo_db']);
        return $mongo;
    }


    //特殊字符转义
    public function pram_deep($value)
    {
        if (empty($value)){return $value;}else{
            return is_array($value)?array_map(array($this,'pram_deep'),$value):mysql_escape_string($value);
        }
    }

    //建立多级目录
    public function createdir($path){
        if (!file_exists($path))
        {
            $this->createdir(dirname($path));
            mkdir($path, 0777);
        }
    }

    //上传文件 file=上传文件的数组或文件地址 path=要在什么目录下 issmall=是否要缩略图 sw=缩略图宽 sh=缩略图高
    public function upload($file,$path='',$issmall=false,$sw=100,$sh=100){
        $webinfo = Lxbase::getconfig("web");
        $pathdir=$webinfo["staticurl"];
        //要生成文件的目录
        $timdir=date("Ymd",time());//根据每天生成一个新目录
        $filedir=$pathdir.'upload/qy/'.$path.'/'.$timdir."/";
        if(!is_dir($filedir)){$this->createdir($filedir);}
        //要生成文件的名字
        $filename=$path.time("is").rand(100,999);
        if(is_array($file)){
            //上传文件
            $hz = pathinfo($file["name"], PATHINFO_EXTENSION);
            if(empty($hz)){
                $hz = array_pop(explode(".",$file["name"]));
            }
            $pic = $filedir.$filename.".".$hz;
            move_uploaded_file($file["tmp_name"],$pic);
        }elseif(!empty($file)){
            //文件地址
            $hz = pathinfo($file, PATHINFO_EXTENSION);
            if(empty($hz)){
                $hz = array_pop(explode(".",$file));
            }
            $pic = $filedir.$filename.".".$hz;
            file_put_contents($pic,file_get_contents($file));
        }else{
            return '';
        }
        //如果有缩略图
        if($issmall && in_array($hz,array('jpg','png','gif','jpeg','bmp'))){
            $spic = $this->getmnimg($pic,0,0,$sw,$sh,$filedir.$filename."_small.".$hz);

            $data["spic"]=$webinfo["updir"].$path.'/'.$timdir.'/'.$filename.'_small.'.$hz;
        }
        $data["pic"]=$webinfo["updir"].$path.'/'.$timdir.'/'.$filename.'.'.$hz;
        return $data;
    }


    //暂存文件并获得文件类型 $data=上传文件数组或文件数据流 $type=当为数据流时要指定文件后缀名
    public function settempfile($data,$type=''){
        $typearr = array(
            array("FFD8FFE0","jpg"),
            array("89504E47","png"),
            array("47494638","gif"),
            array("49492A00","tif"),
            array("424D","bmp"),
            array("41433130","dwg"),
            array("38425053","psd"),
            array("7B5C727466","rtf"),
            array("3C3F786D6C","xml"),
            array("68746D6C3E","html"),
            array("44656C69766572792D646174","eml"),
            array("CFAD12FEC5FD746F","dbx"),
            array("2142444E","pst"),
            array("D0CF11E0","xls/doc"),
            array("5374616E64617264204A","mdb"),
            array("FF575043","wpd"),
            array("252150532D41646F6265","eps/ps"),
            array("255044462D312E","pdf"),
            array("E3828596","pwl"),
            array("504B0304","zip"),
            array("52617221","rar"),
            array("57415645","wav"),
            array("41564920","avi"),
            array("2E7261FD","ram"),
            array("2E524D46","rm"),
            array("000001BA","mpg"),
            array("000001B3","mpg"),
            array("6D6F6F76","mov"),
            array("3026B2758E66CF11","asf"),
            array("4D546864","mid")
        );
        if(is_array($data)){
            $file=$data["tmp_name"];
            $f=fopen($file,'r');
            $bin = fread($f,15);
            fclose($f);
            foreach($typearr as $v){
                $blen=strlen(pack("H*",$v[0])); //得到文件头标记字节数
                $tbin=substr($bin,0,intval($blen)); ///需要比较文件头长度
                if(strtolower($v[0])==@strtolower(array_shift(unpack("H*",$tbin))))
                {
                    $hz = $v[1];
                }
            }
            if(empty($hz)){
                $hz = array_pop(explode(".",$data["name"]));
            }
            $data=file_get_contents($data["tmp_name"]);
        }elseif(!empty($type)){
            $hz=$type;
        }else{
            return '';
        }
        $pic=$_SERVER["DOCUMENT_ROOT"]."/temp/static/temp{$hz}".date("d",time()).rand(1000,9999).".".$hz;
        file_put_contents($pic,$data);
        return $pic;
    }

    //截取图片
    public function getmnimg($imgSrc,$fx=0,$fy=0,$fw=100,$fh=125,$url){
        $srcInfo = getimagesize($imgSrc);
        switch ($srcInfo[2])
        {
            case 1:
                $im =imagecreatefromgif($imgSrc);
                $hz='gif';
                break;
            case 2:
                $im =imagecreatefromjpeg($imgSrc);
                $hz='jpg';
                break;
            case 3:
                $im =imagecreatefrompng($imgSrc);
                $hz='png';
                break;
            case 6:
                $im = imagecreatefromwbmp($imgSrc);
                $hz='jpg';
                break;
            default:
                return '';
                exit;
        }
        if(function_exists("imagecreatetruecolor")) {
            $dim = imagecreatetruecolor($fw,$fh);
        } else {
            $dim = imagecreate($fw,$fh);
        }
        imageCopyreSampled($dim,$im,0,0,$fx,$fy,$fw,$fh,$fw,$fh);
        ob_start();
        switch ($srcInfo[2])
        {
            case 1:
                imagegif($dim);
                break;
            case 2:
                imagejpeg($dim,false,100);
                break;
            case 3:
                imagepng($dim);
                break;
            case 6:
                imagejpeg($dim,false,100);
                break;
            default:
                return '';
                exit;
        }
        $mnimg = ob_get_contents();
        file_put_contents($url,$mnimg);
        return $url;
    }
	
	//生成二维码
	public function getrcode($url=''){
		if(empty($url)){die("urlerror");}
		include(dirname(__FILE__)."/../lib/phpqrcode/qrlib.php");
		$pic = QRcode::png($url,false,4,8,false);
		return $pic;
	}
	
	//转变GPS坐标
	public function getbdgps($long,$lat,$type){
		$url="http://api.map.baidu.com/geoconv/v1/?coords={$long},{$lat}&from={$type}&to=5&ak=6B0lKIOMMPw5O8SG9Lwqv2Gz";
		$bdgps = json_decode($this->call_get($url),true);
		if(!empty($bdgps["result"][0])){
			return $bdgps["result"][0];
		}else{
			return '';
		}
	}


    //错误提示页
    public static function showerror($str,$url){
        $smarty = $this->smarty('public');
        $smarty->assign("errmsg",$errmsg);
        $smarty->assign("url",$url);
        $smarty->display('showerror.tpl');
        return;
    }
}
